﻿var fs = require('fs');
var url = require('url');
var http = require('http');
var server = http.createServer(function(request, response){
	var pathname = url.parse(request.url).pathname;
	
	var file = 'stocks.html';
	var mime = 'text/html';
	if(pathname == '/css') {
		file = 'style.css';
		mime = 'text/css';
	}
	else if(pathname == '/knockout') {
		file = 'knockout-2.0.0.js';
		mime = 'text/plain';
	}
	else if(pathname == '/jquery') {
		file = 'jquery-1.7.1.min.js';
		mime = 'text/plain';
	}
	else if(pathname == '/red') {
		file = 'red.png';
		mime = 'image/png';
	}
	else if(pathname == '/green') {
		file = 'green.png';
		mime = 'image/png';
	}
	
	fs.readFile(__dirname+'/'+file, function(err, data){
		response.writeHead(200, {'Content-Type':mime});
		response.write(data);
		response.end();
	});
});
server.listen(8080);

var nowjs = require("now");
var everyone = nowjs.initialize(server);

var allusers = [];
var winners = [];
var firstUserConnected = false;

// User connect event
nowjs.on('connect', function(){
	if (!firstUserConnected){
		startTimer();
		firstUserConnected = true;
	}
	
	nowjs.getGroup("main").addUser(this.user.clientId);
	nowjs.getGroup(this.now.name).addUser(this.user.clientId);
	
	console.log("Joined: " + this.now.name);
	//everyone.now.receiveMessage('SERVER', this.now.name + ' joined the chat');
	allusers.push(this.now.name);
	everyone.now.repopulateUsers(allusers);
	everyone.now.repopulateCompanies(companyArray);
});

// User disconnect event
nowjs.on('disconnect', function(){
	console.log("Left: " + this.now.name);
	//everyone.now.receiveMessage('SERVER', this.now.name + ' left the chat');
	
	for( var i = 0; i < allusers.length; i++) {
		if(allusers[i] == this.now.name) {
			allusers.splice(i,1);
		}
	}
	
	everyone.now.repopulateUsers(allusers);
});

everyone.now.distributeMessage = function(message,room) {
	if(room != 'main') {
		nowjs.getGroup(this.now.name).now.receiveMessage('&gt; ' + room, message);
	}
	
	if(room == 'main') {
		nowjs.getGroup(room).now.receiveMessage(this.now.name, message);
	}
	else {
		nowjs.getGroup(room).now.receiveMessage(this.now.name + ' &gt; ' + room, message);
	}
};

everyone.now.changeName = function(user) {
	for(var i = 0; i < allusers.length; i++) {
		if(allusers[i] == this.now.name) {
			var oldName = allusers[i];
			allusers[i] = user;
		}
	}
	
	//everyone.now.receiveMessage('SERVER', oldName + ' is now known as ' + user);
	everyone.now.repopulateUsers(allusers);
}

everyone.now.changeRoom = function(room) {
	nowjs.getGroup(room).addUser(this.user.clientId);
};

// Company object
function Company(id, name, stocks, stockPrice, raisedPrice) {
	var self = this;
	self.id = id;
	self.name = name;
	self.stocks = stocks;
	self.stockPrice = stockPrice;
	self.raisedPrice = raisedPrice;
}

var companyArray = [
		new Company(1, 'Apple', randNum(1000, 10000),  randNum(2, 10), true),
		new Company(2, 'IBM', randNum(1000, 10000), randNum(2, 10), true),
		new Company(3, 'Microsoft', randNum(1000, 10000), randNum(2, 10), true),
		new Company(4, 'NASA', randNum(1000, 10000), randNum(2, 10), true),
		new Company(5, 'Facebook', randNum(1000, 10000), randNum(2, 10), true),
		new Company(6, 'Cisco', randNum(1000, 10000), randNum(2, 10), true)
];

// Get the newest company's stock price
everyone.now.getStockPriceByCompanyID = function(company_id, callback) {
	for(var i = 0; i < companyArray.length; i++) {
		if(companyArray[i].id == company_id) {
			return callback(companyArray[i].stockPrice);
		}
	}
	
	return 0;
};

// Update company's stock price
everyone.now.updateStockPrice = function(company_id, stockAmount, raiseStock) {
	for(var i = 0; i < companyArray.length; i++) {
		if(companyArray[i].id == company_id) {
			// The stock price growth formula
			if(raiseStock == true) {
				companyArray[i].stockPrice = Math.round(companyArray[i].stockPrice * 1.1);
				companyArray[i].stocks = companyArray[i].stocks - stockAmount;
			}
			else {
				// The stock price shrink formula
				companyArray[i].stockPrice = Math.round(companyArray[i].stockPrice - (companyArray[i].stockPrice * 0.1));
				companyArray[i].stocks = companyArray[i].stocks + stockAmount;
			}
			
			companyArray[i].raisedPrice = raiseStock;
		}
	}
	
	// Update all clients stock prices
	everyone.now.repopulateCompanies(companyArray);
};

// Get all users
everyone.now.sendStatistics = function(stats) {
	if(winners.length != allusers.length) {
		winners.push(stats);
		//console.log(JSON.stringify(winners));
	}
};

/*
	MISC FUNCTIONS
*/

// Get a random number (from-to)
function randNum(from, to){
	return Math.floor(Math.random() * (to - from + 1) + from);
}

// Do random changes to company
function doRandomChange() {
	var company = randNum(0, companyArray.length-1);
	var raise = ((randNum(0,100) % 2) == 0) ? true : false;
	var percent = randNum(5,50) / 100;
	
	if(companyArray[company] != undefined) {
		console.log('CHANGING!!!');
	
		if(raise) {
			companyArray[company].stockPrice = companyArray[company].stockPrice * (percent + 1)
		}
		else {
			companyArray[company].stockPrice = companyArray[company].stockPrice - (percent * companyArray[company].stockPrice);
		}
		
		companyArray[company].stockPrice = Math.round(companyArray[company].stockPrice);
		companyArray[company].raisedPrice = raise;
		
		// Update all clients stock prices
		everyone.now.repopulateCompanies(companyArray);
	}
}

function startTimer(){
	var globalTimer = 3600;
	setInterval(function() {
		if(globalTimer > 0) {
			globalTimer--;
			everyone.now.updateTimer(globalTimer);
			// Every 2 minutes do some random changes
			if((globalTimer % 120) == 0) {
				doRandomChange();
			}
		}
		// Game is over, display scoreboard
		else {
			winners.sort(function(a, b) {
				return b.credit - a.credit;
			});
			
			everyone.now.showScoreboard(winners);
		}
	}, 1000 );
}